#include <glib.h>

#define TEST_ARRAY_LEN 4

static void _test_hash_str_foreach_func(gpointer key, gpointer value, gpointer user_data)
{
    g_print("%s key: %s, value: %s \n", (gchar *)user_data, (gchar *)key, (gchar *)value);
    return;
}

static void _test_hash_str_key_destroy_func(gpointer data)
{
    if(NULL != data) {
        g_free(data);
    }
}

static void _test_hash_str_value_destroy_func(gpointer data)
{
    if(NULL != data) {
        g_free(data);
    }
}

static void test_hash_get_keys_as_array(void)
{
    gint i = 0;
    guint length = 0;
    gchar **strv = NULL;
    char *key[TEST_ARRAY_LEN] = {NULL};
    char *val[TEST_ARRAY_LEN] = {NULL};
    GHashTable *htable = NULL;

    g_print("\n");

    htable = g_hash_table_new_full(g_str_hash, g_str_equal, \
        _test_hash_str_key_destroy_func, _test_hash_str_value_destroy_func);

    for(i=0; i<TEST_ARRAY_LEN; i++) {
        key[i] = g_strdup_printf("key%d", i);
        val[i] = g_strdup_printf("value%d", i);
        g_print("key[%d](addr:%p): %s \n", i, key[i], key[i]);
        if(1 == i) {
            g_free(val[i]);
            g_hash_table_insert(htable, key[i], NULL);
        } else {
            g_hash_table_insert(htable, key[i], val[i]);
        }
    }

    g_hash_table_foreach(htable, _test_hash_str_foreach_func, "ori");
    g_print("htable length: %d \n", g_hash_table_size(htable));

    strv = (gchar **)g_hash_table_get_keys_as_array(htable, &length);
    for(i=0;i<length;i++) {
        g_print("strv[%d](addr:%p): %s \n", i, strv[i], strv[i]);
    }
    g_strfreev(strv);

    g_hash_table_destroy(htable);

    return;
}

gint main(gint argc, gchar **argv)
{
    g_test_init(&argc, &argv, NULL);

    g_test_add_func ("/hash/search/get-keys-as-array", test_hash_get_keys_as_array);

    return g_test_run();
}